const router = require('koa-router')()
const formidable=require('formidable')
const fs = require('fs');
//获取对应union_id的信息
router.get('/getInfo', async (ctx, next) => {
    const union_id=ctx.request.query.union_id
  
    try {
    const data=await ctx.db.query('SELECT * FROM updraft WHERE union_id = ?', [union_id]);
   if(data[0].img_name==null){
    ctx.body={code:200,data,msg:'查找成功'}
   }else{
    data[0].img_name =fs.readFileSync('./public/images/uploadimgs/'+data[0].img_name).toString('base64')
   }
    ctx.body = { code: 200, data,msg: '查找成功' };
    } catch (e) {
    console.error(e);
    ctx.body = { code: 500, msg: '查找失败' };
    }
    });

    //更新投稿标题内容并存储在数据库表中
router.post('/formUpdate',async(ctx,next)=>{
   
    let value = ctx.request.body
    if(value){
      let sql = 'update updraft set title=?,content=? where union_id=?'
      let res = await ctx.db.query(sql,[value.e.title,value.e.text,value.e.union_id])
    }
    ctx.body={'code':200,'msg':'ok'}
  
  })
   
  //无图片时的更新
  router.post('/deleteImage',async(ctx,next)=>{
    const union_id=ctx.request.body.union_id
    let sql='update updraft set img_name=?,img_type=? where union_id=?'
    await ctx.db.query(sql,[null,null,union_id])
    ctx.body={'code':200,'msg':'ok'}
  })



 //投稿图片并更新在数据库表（updraft）中
router.post('/updateImage', async(ctx,next)=>{
  const form = new formidable.IncomingForm()
  form.keepExtensions = true
  form.multiples=true
    form.parse(ctx.req,async (err,fields,files)=>{  
      const union_id=fields.union_id
      if(files){
        for(key in files){
          let file = files[key]
          const filePath = file.filepath;
          const fileName = Math.random().toString(36).slice(-8)+ '-' + file.originalFilename
          const reader = fs.createReadStream(filePath)
          const write= fs.createWriteStream(`./public/images/uploadimgs/${fileName}`)
          reader.pipe(write)
          let fileExtension = fileName.split('.').pop()
      
          let sql = 'update updraft set img_type=?, img_name=? where union_id=?'
          let res = await ctx.db.query(sql,[fileExtension,fileName ,union_id])
          // console.log(res)
        }
      }else{
        console.log(err);
      }
    })


  ctx.body={'code':200,'msg':'ok'}

})






module.exports =router